//
//  VRVideoViewController.swift
//  VPai
//
//  Created by vicyuan on 16/12/16.
//  Copyright © 2016年 viatech. All rights reserved.
//

import Foundation
import AVFoundation
import Async
import GLKit
import player360


private let TAG = "VRVideoViewController"


class VRVideoViewController: VRViewController {
    
    var playerItem: AVPlayerItem!
    
    private var output : AVPlayerItemVideoOutput!
    private var outputTexture: GLuint = 0
    private var textureCache: CVOpenGLESTextureCacheRef?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置playerItem的输出
        let pixBuffAttributes = [kCVPixelBufferPixelFormatTypeKey as String:
            Int(kCVPixelFormatType_32BGRA)]

        self.output = AVPlayerItemVideoOutput(pixelBufferAttributes: pixBuffAttributes)
        self.playerItem.addOutput(self.output!)
    }
    
    deinit {
      //  Log.info(TAG, msg: "deinit")
    }
    
    func createTextureCacheIfNeed() {
        if textureCache == nil {
            let err: CVReturn = CVOpenGLESTextureCacheCreate(kCFAllocatorDefault, nil, self.context, nil, &textureCache)
            if err != 0 {
           //     Log.error(TAG, msg: "Error at CVOpenGLESTextureCacheCreate: \(err)")
                abort()
            }
        }
    }
    
    func updateTexture() -> Bool {
        var pixelBuffer: CVPixelBuffer?
        let currentTime = self.playerItem.currentTime()
        if self.output.hasNewPixelBufferForItemTime(currentTime) {
            pixelBuffer = self.output.copyPixelBufferForItemTime(currentTime, itemTimeForDisplay: nil)
        }
        
        if pixelBuffer == nil {
            return false
        }
        
        createTextureCacheIfNeed()
        
        outputTexture = GLHelpers.loadVideoTexture(pixelBuffer!, textureCache: textureCache!)

        // Do processing work on the texture data here
        CVOpenGLESTextureCacheFlush(textureCache!, 0)
        
        //CVBufferRelease(pixelBuffer)
        
        return true
    }

    override func glkView(view: GLKView, drawInRect rect: CGRect) {
        if !EAGLContext.setCurrentContext(self.context) {
            return
        }
        
        // update texture
        if !updateTexture() {
        //    Log.debug(TAG, msg: "has no new PixelBuffer")
        }
        
        vrDelegate?.setMediaTexture(outputTexture)
        
        // draw
        vrDelegate?.OnRendererDrawFrame(self.context, rect: rect)
        GLHelpers.checkGlError("VRVideoViewController.glkView")
    }
}
